package com.odata.springboot.starter.odata.odata.sql.process.impl;

import com.odata.springboot.starter.odata.odata.config.OdataConfig;
import com.odata.springboot.starter.odata.odata.sql.process.SqlProcess;
import com.odata.springboot.starter.odata.odata.sql.process.SqlProcessChain;
import com.odata.springboot.starter.odata.odata.sql.sqlBuild.OdataSqlInformation;
import com.odata.springboot.starter.odata.odata.sql.sqlBuild.SqlSyntaxConstants;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * limit 的处理
 * @author chenYX
 * @date 2021/6/28 11:22
 * @description
 */
@Component
public class LimitProcessImpl extends SqlProcess {

    @Autowired
    private SqlProcessChain sqlProcessChain;

    @Override
    public void process(OdataSqlInformation.SqlInformationBuild sqlBuild, UriInfo uriInfo, Class<?> aClass, OData oData) {
        SkipOption skipOption = uriInfo.getSkipOption();
        TopOption topOption = uriInfo.getTopOption();

        if (StringUtils.isEmpty(skipOption) && StringUtils.isEmpty(topOption)){
            //全部为null
            sqlBuild.buildPageFlag(false);
        }else {
            //分页
            sqlBuild.buildPageFlag(true);
            Integer skip = SqlSyntaxConstants.DEFAULT_SKIP;
            Integer top = SqlSyntaxConstants.DEFAULT_TOP;

            if (skipOption != null) {
                skip = skipOption.getValue();
            }

            if (topOption != null){
                top = topOption.getValue();
            }
            sqlBuild.buildPageSkip(skip).buildPageTop(top);

        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.sqlProcessChain.addSqlProcess(this);
    }
}
